package com.sardine.base.threads;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 上海京东到家元信信息技术有限公司<br>
 * Created with IntelliJ IDEA.
 * Date:2017/6/18
 * Time:11:49
 * 缓冲线程线程池工厂
 * @author daifeng<br>
 *         daifeng@imdada.cn
 * @since JDK 1.7 <br>
 * Copyright (c) 2017 imdada System Incorporated All Rights Reserved.
 */
public class CachedThreadPoolExecutorFactory {
    private static final Logger logger = LoggerFactory.getLogger(CachedThreadPoolExecutorFactory.class);

    /**
     * 创建一个线程池
     * @param threadPoolName 线程池名称
     * @param corePoolSize 初始化大小
     * @param maximumPoolSize 组大线程个数
     * @param queueSize 缓存区大小
     * @return
     */
    public static ThreadPoolExecutor createThreadPoolExecutor(String threadPoolName,int corePoolSize,int maximumPoolSize,int queueSize){
        // 异步线程
        ThreadPoolExecutor executor = ThreadPoolUtil.newCachedThreadPool(corePoolSize, maximumPoolSize,
                new LinkedBlockingQueue<Runnable>(queueSize),
                new ThreadNamedFactory(threadPoolName), handler(threadPoolName));
        logger.warn("构建线程池：{}完成。[--初始化大小{}，最大线程数{}，队列最大值{}--]",new Object[]{threadPoolName,corePoolSize,maximumPoolSize,queueSize});
        return executor;
    }

    /**
     * 创建handler
     */
    private static RejectedExecutionHandler handler(final String threadPoolName){

        RejectedExecutionHandler handler = new RejectedExecutionHandler() {
            private int i = 1;
            @Override
            public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                if (i++ % 7 == 0) {
                    i = 1;
                    logger.warn("Task:{} 线程池已经彻底满了!" +
                                    " pool:{}, active:{}, queue:{}, taskcnt: {}",
                            new Object[]{
                                    r,
                                    executor.getPoolSize(),
                                    executor.getActiveCount(),
                                    executor.getQueue().size(),
                                    executor.getTaskCount()
                            });
                }
                throw new RejectedExecutionException(threadPoolName + "  线程池已经彻底满了");
            }
        };
        return handler;
    }

}
